package lsmtree

import (
	"log"
	"lsmtree/config"
	"time"
)

func Check() {
	con := config.GetConfig()
	ticker := time.Tick(time.Duration(con.CheckInterval) * time.Second)
	for range ticker {
		log.Println("Performing background checks...")
		checkMemory()
		database.TableTree.Check()
	}
}

func checkMemory() {
	con := config.GetConfig()
	count := database.MemTable.MemoryTree.GetCount()
	if count < int(con.Threshold) {
		return
	}

	// 将 Memtable 中的数据加入到 iMembertable中
	log.Println("Compressing memory...")
	database.Swap()
}

// CompressMemory会监听 iMemTable，当 iMemberTable 中有数据则进行压缩
func CompressMemory() {
	con := config.GetConfig()
	ticker := time.Tick(time.Duration(con.CompressInterval) * time.Second)
	for range ticker {
		for database.iMemTable.Getlen() != 0 {
			log.Println("Compressing iMemTable...")
			preTable := database.iMemTable.GetTable()
			database.TableTree.CreateNewTable(preTable.MemoryTree.GetValues())
			preTable.Wal.DeleteFile()
		}
	}
}
